import { defineConfig } from "vite";
import uni from "@dcloudio/vite-plugin-uni";
import vueJsx from "@vitejs/plugin-vue-jsx";
import { resolve } from "path";
import Components from "unplugin-vue-components/vite";
import tailwindcss from "tailwindcss";
import autoprefixer from "autoprefixer";
import postcssRemToResponsivePixel from "postcss-rem-to-responsive-pixel";
import postcssWeappTailwindcssRename from "weapp-tailwindcss-webpack-plugin/postcss";
import vwt from "weapp-tailwindcss-webpack-plugin/vite";
import { UnifiedViteWeappTailwindcssPlugin } from "weapp-tailwindcss/vite";
UnifiedViteWeappTailwindcssPlugin({
  rem2rpx: true,
});

const isH5 = process.env.UNI_PLATFORM === "h5";
const isApp = process.env.UNI_PLATFORM === "app";
const weappTailwindcssDisabled = isH5 || isApp;

const postcssPlugin = [autoprefixer(), tailwindcss()];
if (!weappTailwindcssDisabled) {
  postcssPlugin.push(
    postcssRemToResponsivePixel({
      rootValue: 32,
      propList: ["*"],
      transformUnit: "rpx",
    })
  );
  postcssPlugin.push(postcssWeappTailwindcssRename() as any);
}

// import Components from 'unplugin-vue-components/vite'
// https://vitejs.dev/config/
export default defineConfig({
  define: {
    __VUE_I18N_FULL_INSTALL__: true,
    __VUE_I18N_LEGACY_API__: true,
    __VUE_I18N_PROD_DEVTOOLS__: false,
  },
  build: {
    target: "es6",
  },
  resolve: {
    alias: [
      {
        find: "@",
        replacement: resolve(__dirname, "src"),
      },
    ],
  },
  server: {
    port: 1314,
    // 选项写法
    proxy: {
      "/pag": {
        target: "https://cdn.tmui.design",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, "/api"),
      },
    },
  },
  plugins: [
    uni(),
    weappTailwindcssDisabled ? undefined : vwt(),
    vueJsx(),
    Components({
      dts: true,
      resolvers: [
        // example of importing Vant
        (componentName) => {
          if (componentName.startsWith("tm")) {
            return { name: componentName.slice(2), from: "tm" };
          }
        },
      ],
      dirs: ["./src/uni_modules/tm-ui/components"],
      include: [/\.vue$/, /\.uvue$/],
    }),
  ],
  css: {
    postcss: {
      plugins: postcssPlugin,
      // plugins: [
      // 	require('tailwindcss'),
      // 	require('autoprefixer')
      // ],
    },
  },
});
